package com.denlaku.longan.controller.impl;

import com.denlaku.longan.config.LonganProperties;
import com.denlaku.longan.controller.CustomPageController;
import com.denlaku.longan.http.Resp;
import com.denlaku.longan.http.Return;
import com.denlaku.longan.qo.Query;
import com.denlaku.longan.service.CustomApiDataService;
import com.denlaku.longan.service.CustomPageService;
import com.denlaku.longan.util.Lists;
import com.denlaku.longan.util.Objects;
import com.denlaku.longan.vo.CustomApi;
import com.denlaku.longan.vo.CustomApiData;
import com.denlaku.longan.vo.CustomPage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

/**
 * @author tianx
 */
@Slf4j
@Controller
public class CustomPageControllerImpl implements CustomPageController {
    private static final String BASE_PATH = "custom-page";

    private static final String INDEX_HTML = "index.html";

    @Autowired
    private LonganProperties configProperties;

    @Autowired
    private CustomPageService customPageService;

    @Autowired
    private CustomApiDataService customApiService;

    @Override
    public void source(@PathVariable("tenantId") Long tenantId, @PathVariable("id") Long id,
            HttpServletResponse response) {
        sendFile(tenantId, id, INDEX_HTML, response);
    }

    @Override
    public void source(@PathVariable("tenantId") Long tenantId, @PathVariable("id") Long id,
            HttpServletRequest request, HttpServletResponse response) {
        String requestUri = request.getRequestURI();
        String contextPath = request.getContextPath();
        int index = requestUri.indexOf("/", contextPath.length() + 1);
        String name = requestUri.substring(index + 1);
        sendFile(tenantId, id, name, response);
    }

    private void sendFile(Long tenantId, Long id, String name, HttpServletResponse response) {
        try {
            Path path = getFilePath(tenantId, id, name);
            File file = path.toFile();
            if (file.exists() && file.isFile()) {
                Files.copy(path, response.getOutputStream());
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    private Path getFilePath(Long tenantId, Long id, String name) {
        String dir = configProperties.getResourceLocation();
        CustomPage customPage = customPageService.get(Query.of(tenantId, id));
        String zipRoot = Objects.map(customPage, CustomPage::getZipRoot);
        if (StringUtils.isNotEmpty(zipRoot)) {
            return Paths.get(dir, BASE_PATH, String.valueOf(tenantId), String.valueOf(id), zipRoot, name);
        } else {
            return Paths.get(dir, BASE_PATH, String.valueOf(tenantId), String.valueOf(id), name);
        }
    }

    @Override
    @ResponseBody
    public Return<Map<Long, List<Map<String, Object>>>> fetches(@RequestBody List<CustomApi> customApis) {
        List<CustomApiData> list = customApiService.fetches(customApis);
        Map<Long, List<Map<String, Object>>> result = Lists.toMap(list, CustomApiData::getId, CustomApiData::getRows);
        return Resp.success(result);
    }

}
